<template>
  <div>
    <el-card class="search-card" v-loading="formLoading">
      <BasicForm
        v-if="!formLoading"
        ref="formData"
        formItemWidth="120px"
        :formColumns="formItemList"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <BasicTable
        showPagination
        isCustomSort
        showActionCol
        :defaultMinWidth="100"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        :tableHeight="480"
        :actionRender="actionRender"
        :actionColWidth="160"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="total"
        :tableRowClassName="setTableRowClassName"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <div slot="content_context">
            <el-button
              v-if="showBtn('导出')"
              type="primary"
              size="mini"
              icon="el-icon-download"
              :loading="exportLoading"
              @click="exportMaterialToDoList">
              导出
            </el-button>
          </div>
      </BasicTable>
    </el-card>
    <AuditDialog :visible.sync="auditDialogVisible" :todoId="todoId" @getTableData="getTableData" />
    <DisposeDialog :visible.sync="disposeDialogVisible" :todoId="todoId" @disposeCallback="disposeCallback" />
    <AdjustPrice :visible.sync="adjustPriceVisible" :recordNo="recordNo" />
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import BasicTable from '@/components/skusTable';
import AuditDialog from './components/AuditDialog';
import DisposeDialog from './components/DisposeDialog';
import AdjustPrice from './components/AdjustPrice';
import skusPage from '@/mixins/commodity/skusPage';
import { initFormItemList, getTableColumns } from './constants';
import { setAuthBtnId, handleOpenNewPage, createExcelByExport } from '@/utils/bizUtils';
import { queryMaterialToDoListService, queryDropdownService, exportMaterialToDoListService } from '@/api/finance/rawMaterialManage/toDoList';
export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    BasicTable,
    AuditDialog,
    DisposeDialog,
    AdjustPrice
  },
  data () {
    return {
      recordNo: '',
      todoId: null,
      disposeDialogVisible: false, // 处理
      auditDialogVisible: false, // 审核
      adjustPriceVisible: false, // 调价
      formItemList: initFormItemList(),
      formLoading: false,
      formData: {
        name: '',
        state: '',
        floatRadioFrom: '',
        floatRadioTo: '',
        supplyNoOrName: '',
        authDepartmentNo: '',
        unAdjustPriceTimesFrom: '',
        unAdjustPriceTimesTo: '',
        createOpeTime: [],
        associatedRecordCommitTypes: []
      },
      tableInfo: {
        list: [],
        columns: getTableColumns(this),
        loading: false,
        selection: []
      },
      associatedRecordTypes: {
        supplyPrice: 'jinjiaView',
        supplySteelPrice: 'jinjiaViewSteel',
        salePrice: 'sellPriceView',
        saleSteelPrice: 'sellPriceSteelView',
        batchModifySupplyPriceRecord: 'batchModifyPurchaseView',
      },
      sortInfo: {},
      pageSizes: [10, 100, 1000]
    }
  },
  mounted () {
    this.initParams()
    this.getBelongDepartmentData()
    this.getTableData()
  },
  methods: {
    initParams () {
      const { state, overdueDays } = this.$route.query;
      if (state) {
        this.formData.state = state;
      }
      // 超预警日期
      if (overdueDays) {
        this.formData.overdueDays = overdueDays;
      }
    },
    actionRender (h, { row }) {
      // 处理状态：1待处理/2调价中/3待审核/4已处理
      return (
        <div class="table-action">
          <el-button size="mini" type="text" disabled={!this.showBtn('供货信息')} onClick={() => this.handleViewSupplyInfo(row)}>供货明细</el-button>
          <el-button size="mini" disabled={!this.showBtn('处理') || row.state != 1} type="text" onClick={() => this.handleDisposeTodo(row)}>处理</el-button>
          <el-button size="mini" disabled={!this.showBtn('审核') || row.state != 3} type="text" onClick={() => this.handleAuditTodo(row)}>审核</el-button>
        </div>
      );
    },
    // 表格排序
    handleSortTable (data) {
      const { prop, order } = data
      this.sortInfo = {
        orderby: prop,
        orderbyType: order
      }
      this.getTableData()
    },
    // 获取表格数据
    async getTableData () {
      const { floatRadioFrom, floatRadioTo, unAdjustPriceTimesFrom, unAdjustPriceTimesTo } = this.formData;
      if (floatRadioFrom && floatRadioTo && (floatRadioFrom > floatRadioTo)) {
        return this.$message.warning('浮动率起始值不能大于结束值')
      }
      if (unAdjustPriceTimesFrom && unAdjustPriceTimesTo && (unAdjustPriceTimesFrom > unAdjustPriceTimesTo)) {
        return this.$message.warning('连续为调价次数起始值不能大于结束值')
      }
      const [startTime = '', endTime = ''] = this.formData.createOpeTime || [];
      const data = {
        ...this.paginationParams,
        createOpeTimeStart: startTime,
        createOpeTimeEnd: endTime,
        ..._.omit(this.formData, 'createOpeTime'),
      };
      setAuthBtnId();
      const res = await queryMaterialToDoListService(
        data,
        state => { this.tableInfo.loading = state }
      );
      if (res?.retData) {
        this.tableInfo.list = res.retData.results;
        this.total = res.retData.totalNum;
      }
    },
    // 导出信息数据
    async exportMaterialToDoList () {
      const { floatRadioFrom, floatRadioTo, unAdjustPriceTimesFrom, unAdjustPriceTimesTo } = this.formData;
      if (floatRadioFrom && floatRadioTo && (floatRadioFrom > floatRadioTo)) {
        return this.$message.warning('浮动率起始值不能大于结束值')
      }
      if (unAdjustPriceTimesFrom && unAdjustPriceTimesTo && (unAdjustPriceTimesFrom > unAdjustPriceTimesTo)) {
        return this.$message.warning('连续为调价次数起始值不能大于结束值')
      }
      setAuthBtnId();
      const [startTime = '', endTime = ''] = this.formData.createOpeTime || [];
      const data = {
        createOpeTimeStart: startTime,
        createOpeTimeEnd: endTime,
        ..._.omit(this.formData, 'createOpeTime'),
      };
      const res = await exportMaterialToDoListService(
        data,
        state => { this.exportLoading = state; }
      );
      createExcelByExport({ res, excelTitle: '原材料待办列表' });
    },
    // 获取归属部门
    async getBelongDepartmentData () {
      const res = await queryDropdownService(
        {},
        state => { this.formLoading = state }
      );
      if (res.retData) {
        this.formItemList = initFormItemList(res.retData)
      }
    },
    // 供货状态
    handleViewSupplyInfo (row) {
      handleOpenNewPage(this, { name: 'supplyinfoList', query: { supplierCode: row.supplyUuid, categoryUuid: row.associatedCategoryUuids, saleAreaUuid: row.businessAreaNo } })
    },
    // 处理待办
    handleDisposeTodo (row) {
      this.todoId = row.uuid;
      this.recordNo = row.recordNo;
      this.disposeDialogVisible = true;
    },
    // 审核待办
    handleAuditTodo (row) {
      this.todoId = row.uuid;
      this.auditDialogVisible = true;
    },
    // 查看调价单据号详情
    viewRecordDetail (row) {
      if (!row.associatedRecordType) {
        return;
      }
      const routerName = this.associatedRecordTypes[row.associatedRecordType];
      if (row.associatedRecordType == 'batchModifySupplyPriceRecord') {
        handleOpenNewPage(this, { name: routerName, query: { type: 'view', batchNo: row.associatedRecordNo } })
      } else {
        handleOpenNewPage(this, { name: routerName, query: { recordNo: row.associatedRecordNo } })
      }
    },
    // 处理回调
    disposeCallback (row) {
      // 调整售价或进价
      if (row.currentAdjustPriceState == 1) {
        this.adjustPriceVisible = true;
      } else {
        this.getTableData()
      }
    },
    // 表格背景色设置
    setTableRowClassName ({ row, rowIndex }) {
      if (row.unAdjustPriceTimes == 2) {
        return 'warning-row';
      } else if (row.unAdjustPriceTimes > 2) {
        return 'error-row';
      }
      return '';
    }
  }
}
</script>
